package cc.orange.mainView;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.adapter.A12HomeAdapter;
import cc.orange.adapter.HomeAdapter;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentFaceA1Binding;
import cc.orange.entity.ChatListEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.CheckNotifyPermissionUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.popup.PopupShakeView;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class FaceA1ListFragment extends BaseFragment implements View.OnClickListener{
    private SuerInfosEntity entity;
    private A12HomeAdapter adapter;
    private List<ChatListEntity.Data.DataList> list = new ArrayList<>();
    private FragmentFaceA1Binding binding;
    private ZXSharedPrefUtil sharedPrefUtil;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        sharedPrefUtil = new ZXSharedPrefUtil();
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_face_a1,container,false);
        initVies();
        collect();
        chatList();
        EventBus.getDefault().register(this);
        return binding.getRoot();
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(String entity){
        if(entity.equals("home_refres")){
            list.clear();
            chatList();
        }
    }

    private void initVies() {

        if (BuildConfig.UIA.equals("A1")) {// A1面
            binding.face1TitleBack.setBackgroundResource(R.drawable.icon_a1_titleback);
            binding.msglistTitle2.setTextColor(getResources().getColor(R.color.white));
            binding.face1Text1.setTextColor(getResources().getColor(R.color.color_ffff5bf4));
            binding.face1Rel2.setBackgroundResource(R.drawable.shape_face1_bb1);
            binding.face1Rel1.setVisibility(View.VISIBLE);
            binding.face1Rel3.setVisibility(View.GONE);
            binding.homeImg12.setImageResource(R.drawable.icon_a12_msglist_img1);

            binding.shellRetur.setBackgroundResource(R.drawable.shape_login_a12_btn);
            binding.shellRetur.setTextColor(getResources().getColor(R.color.white));

        }else if (BuildConfig.UIA.equals("A2")){// A2面
            binding.face1TitleBack.setBackgroundResource(R.drawable.icon_a2_titleback);
            binding.msglistTitle2.setTextColor(getResources().getColor(R.color.black));
            binding.face1Text1.setTextColor(getResources().getColor(R.color.black));
            binding.face1Rel2.setBackgroundResource(R.drawable.shape_face2_bb2);
            binding.face1Rel3.setVisibility(View.VISIBLE);
            binding.face1Rel1.setVisibility(View.GONE);
            binding.homeImg12.setImageResource(R.drawable.icon_a12_msga2_img12);

            binding.shellRetur.setBackgroundResource(R.drawable.icon_shellike_img1);
            binding.shellRetur.setTextColor(getResources().getColor(R.color.black));
        }else if (BuildConfig.UIA.equals("A5")){// A5面
            binding.face1TitleBack.setBackgroundResource(0);
            binding.msglistTitle2.setTextColor(getResources().getColor(R.color.white));
            binding.face1Text1.setTextColor(getResources().getColor(R.color.white));
            binding.face1Rel2.setBackgroundResource(R.drawable.shape_face2_bb2);
            binding.face1Rel3.setVisibility(View.VISIBLE);
            binding.face1Rel1.setVisibility(View.GONE);
            binding.homeImg12.setImageResource(R.drawable.icon_a5_msga2_img12);

            binding.shellRetur.setBackgroundResource(R.drawable.shape_login_a12_btn);
            binding.shellRetur.setTextColor(getResources().getColor(R.color.white));
        }


        binding.face1Rel0.setOnClickListener(this);
        binding.face1Rel1.setOnClickListener(this);
        binding.face1Rel3.setOnClickListener(this);
        binding.shellShellike.setOnClickListener(this);
        binding.shellRecives.setOnClickListener(this);
        binding.msgRel4.setOnClickListener(this);

        binding.shellRetur.setOnClickListener(this);


        adapter = new A12HomeAdapter(list);
        binding.homeRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.homeRecycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String token_hr = sharedPrefUtil.getString("token_hr");
                boolean isLogin_hr = sharedPrefUtil.getBool("isLogin_hr");
                if(!isLogin_hr || TextUtils.isEmpty(token_hr)){
                    ZXToastUtil.showToast("请先登录");
                    startActivity(new Intent(getActivity(),A12LoginActivity.class));
                    return;
                }
                Intent intent = new Intent(getActivity(), A12ConversationListActivity.class);
                intent.putExtra("uid", "" + list.get(position).getWomanId());
                intent.putExtra("u_name", "" + list.get(position).getName()); intent.putExtra("u_name",
                        ""+(TextUtils.isEmpty(list.get(position).getRemarkName()) ?
                                list.get(position).getName() : list.get(position).getRemarkName()));
                intent.putExtra("u_spare", "" + list.get(position).getSpareStatus());
                intent.putExtra("type_t", "1");
                startActivity(intent);

                list.get(position).setUnreadNum(0);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        String token_hr = sharedPrefUtil.getString("token_hr");
        boolean isLogin_hr = sharedPrefUtil.getBool("isLogin_hr");
        if(!isLogin_hr || TextUtils.isEmpty(token_hr)){
            ZXToastUtil.showToast("请先登录");
            startActivity(new Intent(getActivity(),A12LoginActivity.class));
            return;
        }
        switch (v.getId()){
            case R.id.face1_rel1://A1
                binding.face1Rel4.setVisibility(View.GONE);
                binding.layouRals2.setVisibility(View.VISIBLE);
                break;
            case R.id.face1_rel3://A2
                binding.face1Rel4.setVisibility(View.GONE);
                binding.layouRals2.setVisibility(View.VISIBLE);
                break;
            case R.id.face1_rel0://通知
                RequestPermissions.getPermissions_notfi(getActivity(), new RequestPermissions.SuccessInterf() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess() {
                        if(entity != null && entity.getData() != null ){
                            entity.getData().getNewsRemind().equals("1");
                            updateNotify();
                        }else{
                            binding.face1Rel0.setVisibility(View.GONE);
                        }

                    }
                });
                break;
            case R.id.shell_retur://回应
                if (list.size() <= 0) {
                    ZXToastUtil.showToast("暂时还没人回应你");
                } else {
                    Intent intent = new Intent(getActivity(), ConversationListActivity.class);
                    intent.putExtra("uid", "" + list.get(0).getWomanId());
                    intent.putExtra("u_name", "" + list.get(0).getName());
                    intent.putExtra("u_spare", "" + list.get(0).getSpareStatus());
                    intent.putExtra("type_t", "1");
                    startActivity(intent);

                    list.get(0).setUnreadNum(0);
                    adapter.notifyDataSetChanged();
                }
                break;
            case R.id.shell_shellike://悄悄话
                PopupShakeView(1);
                break;
            case R.id.shell_recives://收一条
                collect();
                break;
            case R.id.msg_rel4://重要通知
                startActivity(new Intent(getActivity(), A12ConverNotesFActivity.class));
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(SuerInfosEntity entity){
        if(entity.getCode() == 0){
            this.entity = entity;
            RequestOptions qe = new RequestOptions();
            qe.error(entity.getData().getSex() == 1 ? R.drawable.icon_login_img3:R.drawable.icon_login_img4);
            Glide.with(getActivity()).load(entity.getData().getHeadPhoto()).apply(qe).into(binding.face1Img1);

            binding.face1Text2.setText((entity.getData().getSex() == 1 ? "♂ ":"♀ ")+entity.getData().getName());

            checkNotf();
        }else{

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void checkNotf() {
        boolean b1 = CheckNotifyPermissionUtils.checkNotifyPermission(getActivity());
        if(entity == null || entity.getData() == null){
            binding.face1Rel0.setVisibility(View.GONE);
        }else {
            if (entity.getData().getNewsRemind().equals("0")) {//是否开启消息提醒(0关闭,1开启)
                binding.face1Rel0.setVisibility(View.VISIBLE);
            } else if (entity.getData().getNewsRemind().equals("1") && b1) {//是否开启消息提醒(0关闭,1开启)
                binding.face1Rel0.setVisibility(View.GONE);
            } else {
                binding.face1Rel0.setVisibility(View.VISIBLE);
            }
        }
    }


    private void updateNotify(){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
        entitys.setNewsRemind("1");
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            ZXToastUtil.showToast("已开启聊天消息提醒");
                            EventBus.getDefault().post(new String("getsus"));
                        }else{
                        }
                    }
                });
    }


    private void chatList() {
        RetrofitFactory.create(ApiService.class)
                .chatList(getTokens(),"1")//消息列表类型(0首页消息,1悄悄话消息)
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            list.addAll(baseEntity.getData().getDataList());
                            adapter.notifyDataSetChanged();
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }



    private void PopupShakeView(int types) {
        PopupShakeView.showPopupwindow(getActivity(), binding.homeImg12, new PopupShakeView.PopuStatus() {
            @Override
            public void popupShow() {

            }

            @Override
            public void popupDismissCancle(String se1) {
                holeAdd(se1);
            }
        });
    }

    private void holeAdd(String contents) {
        String s = "{\"sendContent\":\"" + contents + "\"}";
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .holeAdd(getTokens(), requestBody1)
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXToastUtil.showToast("已扔进树洞");
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    private void collect() {
        RetrofitFactory.create(ApiService.class)
                .collect(getTokens())
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            list.clear();
                            chatList();
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }
}